package com.ch.d0312.d0316;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(name = "GetUploadServlet", value = "/GetUploadServlet")
public class GetUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        // 获取资源路径
        final String url = req.getRequestURI();
        //提取文件名
        final String filename = url.replaceAll(".+/upload/(.+)", "$1");
        //设置返回的内容类型
        // html ==> text/html, jpg ==> image/jpeg
        final String mineType = req.getServletContext().getMimeType(filename);
        resp.setContentType(mineType);
        // 将文件返回给浏览器
        // java.io 流
        String path = UploadImageServlet.IMAGE_PATH + filename;
        try (FileInputStream fis = new FileInputStream(path)) {
            byte[] buffer = new byte[1024];
            int count;
            final ServletOutputStream out = resp.getOutputStream();
            while ((count = fis.read(buffer)) > -1) {
                out.write(buffer, 0, count);
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
